//
//  DB.m
//  DataBase
//
//  Created by dllo on 15/8/14.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "DB.h"
#import <sqlite3.h>
static sqlite3 *dbPoint = nil; //数据库指针
@implementation DB


//因为源文件无法进行修改,所以将bundle 中得数据库拷贝到其他三个文件夹中(document,library,tmp)中进行操作

+ (sqlite3 *)dbOpen
{
    //如果指针存在,则不执行下面代码,不往下走
    if (dbPoint) {
        return dbPoint;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Medicine" ofType:@"rdb"];
    
    NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    toPath = [NSString stringWithFormat:@"%@/medicine.db", toPath];
    NSLog(@"%@",toPath);
    NSFileManager *file = [NSFileManager defaultManager];
    
    if (![file fileExistsAtPath:toPath]) {
        [file copyItemAtPath:path toPath:toPath error:nil];
    }else
    {
        NSLog(@"---文件已存在---%@", toPath);
    }
    
    //将字符串转换成const char 类型
//    [toPath cStringUsingEncoding:NSUTF8StringEncoding];
    
    sqlite3_open([toPath cStringUsingEncoding:NSUTF8StringEncoding], &dbPoint);
    return dbPoint;
}

+(void)dbColse
{
    sqlite3_close(dbPoint);
}

@end
